package com.gt.web.srv.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.web.api.common.R;
import com.gt.web.api.exception.BusinessException;
import com.gt.web.srv.domain.SsUser;
import com.gt.web.srv.mapper.SsUserMapper;
import com.gt.web.srv.mapstructs.SsUserStruct;
import com.gt.web.srv.service.SsUserService;
import com.gt.web.srv.web.api.command.WxLoginReqCommand;
import com.gt.web.srv.web.api.request.UserRequest;
import com.gt.web.srv.web.api.resource.ResponseUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author jh
 * @Date 2024/5/16 21:49
 * @PackageName:com.gt.web.srv.service.impl
 * @ClassName: ArticleServiceImpl
 * @Description: TODO
 */
@Service
@Slf4j
public class SsUserServiceImpl extends ServiceImpl<SsUserMapper, SsUser> implements SsUserService {

    @Autowired
    private WxMaService wxMaService;


    @Override
    public SsUser getByOpenId(String openId) {
        return baseMapper.selectByOpenId(openId);
    }

    @Override
    public SsUser getByPeopleCard(String peopleCard) {
        return baseMapper.selectByPeopleCard(peopleCard);
    }

    /**
     * 更新用户头像
     * @param userId 用户ID
     * @param nickName 昵称
     * @param avatarUrl 头像
     * @return
     */
    @Override
    public boolean updateWechatInfo(Long userId, String nickName, String avatarUrl) {
        SsUser user = baseMapper.selectById(userId);
        if (user != null) {
            user.setOpenNick(nickName);
            user.setOpenAvatarUrl(avatarUrl);
            return updateById(user);
        }
        return false;
    }


    @Override
    public R<ResponseUserVo> login(WxLoginReqCommand reqDto) {
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(reqDto.getCode());
            if (ObjectUtil.isNull(session) || StringUtils.isBlank(session.getOpenid())) {
                throw new BusinessException(500, "获取微信信息失败，请稍后重试");
            }
            log.info("微信session: {}", JSONUtil.toJsonStr(session));
            String openId = session.getOpenid();
//             String openId = "o0OIL7QCLknqQK-3MOMn1m3ELpfU";
            SsUser peopleRepDto = baseMapper.selectByOpenId(openId);
            if (Objects.isNull(peopleRepDto)) {
                peopleRepDto = new SsUser();
                peopleRepDto.setOpenId(openId);
                peopleRepDto.setUnionId(openId);
                baseMapper.insert(peopleRepDto);
            }
            //采用jwt生成token
            ResponseUserVo user = SsUserStruct.INSTANCE.toResponseUserVo(peopleRepDto);
            return R.ok(user);
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @Override
    public boolean saveOrUpdateByUserId(UserRequest userRequest) {
        SsUser ssUser = SsUserStruct.INSTANCE.simple(userRequest);
        if (ssUser.getUserId() == null) {
            // 新增
            baseMapper.insert(ssUser);
        } else {
            // 更新
            baseMapper.updateById(ssUser);
        }
        return true;
    }

    @Override
    public SsUser getByUserId(Long userId) {
        return baseMapper.selectById(userId);
    }
}